import React, { Component } from "react";
import {
  StyleSheet,
  View,
  Text,
  Switch,
  Picker,
  TouchableOpacity,
  Image
} from "react-native";
import Button from "../../components/Button";
import { connect } from "react-redux";
import HeaderDefault from "../../components/header/HeaderDefault";
import { theme_app, theme_text, theme_btnColor } from "../../utils/appTheme";
import Modal from "../../components/ModalBox";

import DateTimePicker from "../../components/datetimePicker";
import { dateTransform } from "../../utils/utils_date";
import { addOxyRec, modifyTourOxygen } from "../../netServer/patrol";
import Toast from "react-native-simple-toast";
import PatientBaseHeader from "./PatientBaseHeader";
import { patientBaseInfo } from "../../netServer/signs_net";

class OxygenAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isInBed: true,
      isCommitSuccess: false,
      P_b_info: {},//患者基本信息
      dateTimePickerStyle: "start",
      isDateTimePickerVisible: false,
      endTime: new Date(),
      startTime: new Date(),
      xiYangFangshi: "持续",
      xiYangLiang: "中流量"
    };

    this.modalSty = "fangshi";
    this._loadPatienBaseInfo = this._loadPatienBaseInfo.bind(this);
  }

  static navigationOptions = ({ navigation }) => ({
    gesturesEnabled: false,
    header: (
      <HeaderDefault
        backBtnOnPress={() => {
          let { currentRouterKey } = navigation.state.params;
          navigation.goBack(currentRouterKey);
        }}
        // backBtnOnPress={navigation.goBack}
        title={navigation.state.params.title}
      />
    )
  });

  openModal = modalStyString => {
    this.modalSty = modalStyString;
    if (modalStyString === "fangshi") {
      this.myModel1.open();
    } else {
      this.myModel2.open();
    }
  };

  componentDidMount() {
    this._mInitData();
    this._loadPatienBaseInfo()
  }


  _loadPatienBaseInfo() {

    let { patient_no } = this.props.navigation.state.params.pinfo;

    let formData = new FormData()
    formData.append('pno', patient_no)

    // name sex birthday bed_no allergy


    patientBaseInfo(formData, resp => {
      let { code, msg, data = {} } = resp

      if (code == '0') {
        let { identityInfo = {} } = data
        let { name, birthDate, bed, sex, allegy } = identityInfo

        let ne_p = {
          name: name,
          sex: sex,
          birthday: birthDate,
          bed_no: bed,
          allergy: allegy,
        }
        this.setState({
          P_b_info: ne_p,
        })
      }
    })
  }


  _mInitData = () => {
    // taskInfo

    let { isEditer, taskInfo = {} } = this.props.navigation.state.params;
    if (isEditer) {
      let { start_time, end_time, use_way, flow_grade } = taskInfo;

      let state_date = start_time
        ? new Date(start_time.replace(/-/g, "/"))
        : new Date();
      let end_date = end_time
        ? new Date(end_time.replace(/-/g, "/"))
        : new Date();

      this.setState({
        endTime: end_date,
        startTime: state_date,
        xiYangFangshi: use_way,
        xiYangLiang: flow_grade
      });

      // { oxy_rec_id: 2,
      //   patient_no: '14f9026f2c76832692538e1f28c1671b',
      //   create_at: '2019-03-19 16:52:02',
      //   create_by: 'bf5eb52d6491564b7d7f5569c9909b2f',
      //   bed_rec_id: 150,
      //   start_time: '2019-03-19 16:52:00',
      //   end_time: '2019-03-19 16:52:00',
      //   use_way: '持续',
      //   oxygen_flow: null,
      //   flow_unit: null,
      //   update_at: null,
      //   update_by: null,
      //   delete_flag: 0,
      //   flow_grade: '中流量',
      //   record_by: 'bf5eb52d6491564b7d7f5569c9909b2f',
      //   notes: null }
    }
  };

  _renderModalBox2 = () => {
    return (
      <Modal
        style={styles.modal3}
        position={"bottom"}
        backdropPressToClose={false}
        swipeToClose={false}
        ref={md => (this.myModel2 = md)}
      >
        <View style={{ flex: 1 }}>
          <View
            style={{
              width: screenWidth,
              height: 50,
              flexDirection: "row-reverse",
              alignItems: "center"
            }}
          >
            <TouchableOpacity
              onPress={() => {
                this.myModel2.close();
              }}
              style={{
                width: 50,
                height: 50,
                justifyContent: "center",
                alignItems: "center"
              }}
            >
              <Image
                style={{ width: 30, height: 30 }}
                source={require("./src/guanbi.png")}
              />
            </TouchableOpacity>
          </View>

          <Picker
            selectedValue={this.state.xiYangLiang}
            style={{ height: 150, width: screenWidth }}
            onValueChange={(itemValue, itemIndex) =>
              this.setState({ xiYangLiang: itemValue })
            }
          >
            <Picker.Item label="低流量" value="低流量" />
            <Picker.Item label="中流量" value="中流量" />
            <Picker.Item label="高流量" value="高流量" />
          </Picker>
        </View>
      </Modal>
    );
  };

  _renderModalBox = () => {

    return (
      <Modal
        style={styles.modal3}
        position={"bottom"}
        backdropPressToClose={false}
        swipeToClose={false}
        ref={md => (this.myModel1 = md)}
      >
        <View style={{ width: screenWidth, height: 200 }}>
          <View
            style={{
              width: screenWidth,
              height: 50,
              flexDirection: "row-reverse",
              alignItems: "center"
            }}
          >
            <TouchableOpacity
              onPress={() => {
                this.myModel1.close();
              }}
              style={{
                width: 50,
                height: 50,
                justifyContent: "center",
                alignItems: "center"
              }}
            >
              <Image
                style={{ width: 30, height: 30 }}
                source={require("./src/guanbi.png")}
              />
            </TouchableOpacity>
          </View>

          <Picker
            selectedValue={this.state.xiYangFangshi}
            style={{ height: 150, width: screenWidth }}
            onValueChange={(itemValue, itemIndex) =>
              this.setState({ xiYangFangshi: itemValue })
            }
          >
            <Picker.Item label="持续" value="持续" />
            <Picker.Item label="间歇" value="间歇" />
            <Picker.Item label="双鼻吸氧" value="双鼻吸氧" />
            <Picker.Item label="面罩吸氧" value="面罩吸氧" />
          </Picker>
        </View>
      </Modal>
    );
  };

  _showDateTimePicker = styleStr =>
    this.setState({
      isDateTimePickerVisible: true,
      dateTimePickerStyle: styleStr
    });

  _hideDateTimePicker = () => this.setState({ isDateTimePickerVisible: false });

  _handleDatePicked = date => {
    if (this.state.dateTimePickerStyle === "start") {
      this.setState({
        startTime: date
      });
    } else {
      this.setState({
        endTime: date
      });
    }
    this._hideDateTimePicker();
  };

  addOxygen = () => {
    let { isEditer } = this.props.navigation.state.params;

    if (isEditer) {
      this.upDateOxygen();

      return;
    }

    let params = new FormData();
    let { patient_no } = this.props.navigation.state.params.pinfo;
    let { user_id } = this.props.user_info;

    params.append("patient_no", patient_no);
    params.append("create_by", user_id);
    params.append(
      "start_time",
      dateTransform(this.state.startTime, "yyyy-MM-dd hh:mm:ss")
    );
    params.append(
      "end_time",
      dateTransform(this.state.endTime, "yyyy-MM-dd hh:mm:ss")
    );
    params.append("use_way", this.state.xiYangFangshi);
    params.append("flow_grade", this.state.xiYangLiang);

    addOxyRec(params, resp => {
      let { code, msg } = resp;

      this.setState({
        isCommitSuccess: code == "0"
      }, this.CenterModel.open())


      // if (code == "0") {
      //   this.props.navigation.state.params.commitSuccessCB();

      //   let { currentRouterKey } = this.props.navigation.state.params;

      //   if (currentRouterKey) {
      //     this.props.navigation.goBack(currentRouterKey);
      //   } else {
      //     this.props.navigation.goBack();
      //   }
      // }
      // Toast.showWithGravity(msg, 0.3, Toast.CENTER);
    });
  };

  upDateOxygen = () => {
    let { taskInfo = {} } = this.props.navigation.state.params;

    let params = new FormData();
    let { user_id } = this.props.user_info;

    params.append("oxy_rec_id", taskInfo.oxy_rec_id);
    params.append("update_by", user_id);
    params.append(
      "start_time",
      dateTransform(this.state.startTime, "yyyy-MM-dd hh:mm:ss")
    );
    params.append(
      "end_time",
      dateTransform(this.state.endTime, "yyyy-MM-dd hh:mm:ss")
    );
    params.append("use_way", this.state.xiYangFangshi);
    params.append("flow_grade", this.state.xiYangLiang);

    modifyTourOxygen(params, resp => {
      let { code, msg } = resp;
      if (code == "0") {
        this.props.navigation.state.params.commitSuccessCB();
        this.props.navigation.goBack();
      }


      Toast.showWithGravity(msg, 0.3, Toast.CENTER);
    });
  };

  renderModalContent = () => {
    return (
      <View style={{ flex: 1, alignItems: 'center', }}>
        <Text style={{ color: 'red', fontSize: 16, fontWeight: '600', paddingTop: 15, paddingBottom: 15, }}>
          {this.state.isCommitSuccess ? "提交成功" : "提交失败"}
        </Text>

        <Text style={{ paddingLeft: 15, paddingRight: 15, fontSize: 14, paddingTop: 20, paddingBottom: 20 }}>

          {this.state.isCommitSuccess ? "您已成功提交吸氧巡视，是否返回扫码页面继续扫码添加" : "对不起！您的吸氧巡视提交失败"}

        </Text>

        <View style={{ flexDirection: 'row' }}>

          <Button
            style={[
              styles.buttonCommit,
              { backgroundColor: '#33A3F4', width: 100, height: 40 }
            ]}
            onPress={() => {
              if (this.state.isCommitSuccess) {
                this.props.navigation.state.params.commitSuccessCB();
                this.props.navigation.goBack();
              } else {
                this.CenterModel.close();
              }
            }}
          >
            <Text
              style={{
                fontSize: 16,
                color: theme_text.background_Color
              }}
            >
              {this.state.isCommitSuccess ? "继续扫码" : "确定"}
            </Text>
          </Button>
          <View style={{ width: 20 }} />

          <Button
            style={[
              styles.buttonCommit,
              { backgroundColor: "green", width: 100, height: 40 }
            ]}

            onPress={() => {
              let { currentRouterKey } = this.props.navigation.state.params;
              this.props.navigation.goBack(currentRouterKey);
            }}
          >
            <Text
              style={{
                fontSize: 16,
                color: theme_text.background_Color
              }}
            >
              返回首页
            </Text>
          </Button>

        </View>


      </View>
    )
  }

  render() {
    return (
      <View style={styles.container}>

        <PatientBaseHeader baseInfo={this.state.P_b_info} />

        <View
          style={[
            styles.limeItem,
            {
              flexDirection: "row",
              alignItems: "center",
              paddingLeft: 10,
              paddingRight: 10
            }
          ]}
        >
          <Text style={{ fontSize: 15 }}>开始时间:</Text>
          <TouchableOpacity
            onPress={() => {
              this._showDateTimePicker("start");
            }}
            style={{
              flex: 1,
              justifyContent: "center",
              alignItems: "center"
            }}
          >


            <Text>{dateTransform(this.state.startTime, "hh:mm")}</Text>
          </TouchableOpacity>
        </View>

        <View
          style={[
            styles.limeItem,
            {
              flexDirection: "row",
              alignItems: "center",
              paddingLeft: 10,
              paddingRight: 10
            }
          ]}
        >
          <Text style={{ fontSize: 15 }}>结束时间:</Text>
          <TouchableOpacity
            onPress={() => {
              this._showDateTimePicker("end");
            }}
            style={{
              flex: 1,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text>{dateTransform(this.state.endTime, "hh:mm")}</Text>
          </TouchableOpacity>
        </View>

        <View
          style={[
            styles.limeItem,
            {
              flexDirection: "row",
              alignItems: "center",
              paddingLeft: 10,
              paddingRight: 10
            }
          ]}
        >
          <Text style={{ fontSize: 15 }}>吸氧方式:</Text>
          <TouchableOpacity
            onPress={() => {
              this.openModal("fangshi");
            }}
            style={{
              flex: 1,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text>{this.state.xiYangFangshi}</Text>
          </TouchableOpacity>
        </View>

        <View
          style={[
            styles.limeItem,
            {
              flexDirection: "row",
              alignItems: "center",
              paddingLeft: 10,
              paddingRight: 10
            }
          ]}
        >
          <Text style={{ fontSize: 15 }}>吸&nbsp;&nbsp;氧&nbsp;&nbsp;量:</Text>
          <TouchableOpacity
            onPress={() => {
              this.openModal("xiyangliang");
            }}
            style={{
              flex: 1,
              justifyContent: "center",
              alignItems: "center"
            }}
          >
            <Text>{this.state.xiYangLiang}</Text>
          </TouchableOpacity>
        </View>

        <View
          style={{
            width: screenWidth,
            height: 80,
            justifyContent: "center",
            alignItems: "center"
          }}
        >
          <Button
            style={[
              styles.buttonCommit,
              { backgroundColor: theme_btnColor.main_color }
            ]}
            onPress={this.addOxygen}
          >
            <Text
              style={{
                fontSize: 18,
                color: theme_text.background_Color
              }}
            >
              提交
            </Text>
          </Button>
        </View>

        {this._renderModalBox()}
        {this._renderModalBox2()}

        <DateTimePicker
          mode="datetime"
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this._handleDatePicked}
          onCancel={this._hideDateTimePicker}
        />

        <Modal
          style={styles.modalCenter}
          position={"bottom"}
          backdropPressToClose={false}
          swipeToClose={false}
          ref={md => (this.CenterModel = md)}
        >
          {this.renderModalContent()}
        </Modal>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: theme_app.bg_color
  },
  limeItem: {
    width: screenWidth,
    height: 45,
    backgroundColor: "white",
    borderBottomColor: "#efefef",
    borderBottomWidth: 1
  },
  modal3: {
    height: 250,
    width: screenWidth
    // justifyContent: 'center',
    // alignItems: 'center'
  },

  modalCenter: {
    height: 200,
    width: screenWidth
  },
  buttonCommit: {
    width: 200,
    // height: 46,
    borderRadius: 6
  }
});

function select(store) {
  return { user_info: store.userInfo.user_info };
}

export default connect(select)(OxygenAdd);
